package com.example.demo01.Controller.webController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.demo01.Entity.webEntity.WarnRecordEntity;
import com.example.demo01.Service.webService.WarnRecordEntityService;
import com.example.demo01.utils.DateParseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.function.Consumer;

@RestController
public class WarnRecordEntityController {

    @Autowired
    WarnRecordEntityService warnRecordEntityService;

    /**
     * 获取报警省份信息
     */
    @RequestMapping("/warnrecord/province")
    public String getProvinceOfWarn() {
        return JSON.toJSONString(warnRecordEntityService.getProvinceOfWarn());
    }

    /**
     * 根据省份编码获取报警市级信息
     *
     * @param provinceCode 省份编码
     */
    @RequestMapping("/warnrecord/province/city")
    public String getCityOfWarn(
            @RequestParam(value = "code") String provinceCode
    ) {
        return JSON.toJSONString(warnRecordEntityService.getCityOfWarn(provinceCode));
    }

    /**
     * 根据市级编码获取报警县区信息
     */
    @RequestMapping("/warnrecord/province/city/country")
    public String getCountryOfWarn(
            @RequestParam(value = "code") String cityCode
    ) {
        return JSON.toJSONString(warnRecordEntityService.getCountryOfWarn(cityCode));
    }

    /**
     * 获取所有报警信息
     * */
    @RequestMapping("/warnrecord/GET/all")
    public String getAllWarnRecords() { return JSON.toJSONString(warnRecordEntityService.getAllWarnRecords()); }

    /**
     * 获取待处理的报警信息
     * */
    @RequestMapping("/warnrecord/GET/unresolved")
    public String getUnResolvedWarnRecords() { return  JSON.toJSONString(warnRecordEntityService.getUnResolvedWarnRecords()); }


    @RequestMapping(value = "/warnrecord/GET/info",method = RequestMethod.POST)
    public String variableParams(
            @RequestBody(required = true) String resMsg
    ){
        //结果集
        List<WarnRecordEntity> warnRecordEntityList=new ArrayList<>();
        //行政区划代码
        String provinceName="",cityName="",countryName="";
        //时间限定
        String timeStart="",timeEnd="";
        //筛选条件界定
        boolean isChinaCodeLimited=false,//行政区划筛选标志位
                isTimeLimited=false;//时间限定标志位
        //时间限定结果
        List<WarnRecordEntity> listresByTime=new ArrayList<>();
        //异常处理
        try {
            JSONObject jsonObject = JSONObject.parseObject(resMsg);
            //获取信息体
            Object msg = jsonObject.get("msg");
            //解析信息体
            JSONObject msgJsonObject = JSONObject.parseObject(msg.toString());
//            System.out.println(msgJsonObject);
            //解析msgJsonObject
            provinceName = msgJsonObject.get("provinceName").toString().trim();
            cityName = msgJsonObject.get("cityName").toString().trim();
            countryName = msgJsonObject.get("countryName").toString().trim();
            timeStart = msgJsonObject.get("timeStart").toString().trim();
            timeEnd = msgJsonObject.get("timeEnd").toString().trim();

            //获取筛选条件
            if (provinceName.length()>0||
                    cityName.length()>0||
                    countryName.length()>0)
                isChinaCodeLimited=true;
            if (timeStart.length()>0||
                    timeEnd.length()>0)
                isTimeLimited=true;
            //1-行政区划筛选
            if (isChinaCodeLimited){
                if ((countryName.length() > 0)) {
                    //执行对应的数据表查询语句——县区
                    warnRecordEntityList = warnRecordEntityService.getWarnRecordByCountryCode(countryName);
                }
                else if ((cityName.length() > 0)) {
                    //执行对应的数据表查询语句——市级
                    warnRecordEntityList = warnRecordEntityService.getWarnRecordByCityCode(cityName.substring(0,4));
                }
                else if (provinceName.length()>0){
                    //执行对应的数据表查询语句——省级
                    warnRecordEntityList = warnRecordEntityService.getWarnRecordByProvinceCode(provinceName.substring(0,2));
                }
                //判断结果集是否为空
                if (warnRecordEntityList.size()>0){
                    //2-时间限定
//                    Long startTime=0L,endTime=0L;
                    if (isTimeLimited){
                        //如果时间限定有效，根据时间区间执行元素筛选
                        Long startTime=Long.parseLong(timeStart);
                        Long endTime=Long.parseLong(timeEnd);
                        warnRecordEntityList.forEach(new Consumer<WarnRecordEntity>() {
                            @Override
                            public void accept(WarnRecordEntity warnRecordEntity) {
                                try {
                                    //DateParseUtils.getDateByDateFormatStr("yyyy-MM-dd HH:mm:ss", "2019-11-30 20:18:48.0").getTime()
                                    long time = DateParseUtils.getDateByDateFormatStr("yyyy-MM-dd HH:mm:ss", warnRecordEntity.getWarntime()).getTime();
                                    if ((time- startTime)>=0&&
                                            (endTime -time) >=0)
                                    {
                                        warnRecordEntity.setId(listresByTime.size()+1);
                                        listresByTime.add(warnRecordEntity);
                                    }
                                } catch (ParseException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                        return JSON.toJSONString(listresByTime);
                    }
                }
            }else{
                //2-时间限定筛选
                if (isTimeLimited){
                    //毫秒数转日期对象
                    Date startDate = DateParseUtils.millionsToUtilDate(Long.parseLong(timeStart));
                    Date endDate = DateParseUtils.millionsToUtilDate(Long.parseLong(timeEnd));
                    //日期对象格式化
                    String dateStartStr = DateParseUtils.getDateStrByFormat(startDate, "yyyy-MM-dd HH:mm:ss");
                    String dateEndStr = DateParseUtils.getDateStrByFormat(endDate, "yyyy-MM-dd HH:mm:ss");
                    //执行SQL语句
                    warnRecordEntityList = warnRecordEntityService.getWarnRecordByTimeLimted(dateStartStr,dateEndStr);
                }
            }
            return JSON.toJSONString(warnRecordEntityList);
        }catch (Exception e){
            return JSON.toJSONString(warnRecordEntityList);
        }
    }


    /**
     * 根据行政区划范围获取报警信息点集合
     * @param bounds 行政区划范围顶点数组
     * */
    @RequestMapping(value = "/warnrecord/GET/boundlimits")
    public String getWarnRecordByBounds(
            @RequestBody(required = true) String bounds){
        System.out.println(bounds);
        return JSON.toJSONString(warnRecordEntityService.getWarnRecordByBounds(bounds));
    }


    /**
     * 根据矩形范围获取报警信息点的集合
     * */
    @RequestMapping(value = "/warnrecord/GET/rectangle")
    public String getWarnRecordByRectangle(
            @RequestBody(required = true) String vertexColls
    ){
        System.out.println(vertexColls);
        return JSON.toJSONString(warnRecordEntityService.getWarnRecordByRectangle(vertexColls));
    }

    /**
     * 根据指定的四个边界范围获取报警信息点的集合
     * @param north 北界
     * @param east 东界
     * @param south 南界
     * @param west 西界
     * */
    @RequestMapping(value = "/warnrecord/GET/boundpts")
    public String getWarnRecordByBoundPts(
            @RequestParam(value = "north") String north,
            @RequestParam(value = "east") String east,
            @RequestParam(value = "south") String south,
            @RequestParam(value = "west") String west
    ){
//        System.out.println(north);
//        System.out.println(east);
//        System.out.println(south);
//        System.out.println(west);
        return JSON.toJSONString(warnRecordEntityService.getWarnRecordByBoundPts(north,east,south,west));
    }

    /**
     * 根据用户身份证号获取用户详细的报警信息
     * @param idnum
     * @return WarnDetail实例
     */
    @RequestMapping(value = "/warndetail/GET/entity")
    public String getWarnDetailByIdnum(
            @RequestParam(value = "idnum") String idnum) {
        return JSON.toJSONString(warnRecordEntityService.getWarnDetailByIdnum(idnum));}


    /**
     * 根据详细信息更新报警信息记录
     * @param admin 管理员用户名
     * @param idnum 身份证号码
     * @param warntime 报警时间
     * @param lon 经度
     * @param lat 纬度
     * @return 影响行数
     */
    @RequestMapping("/warnrecord/UPDATE/byidnum")
    public int updateWarnRecord(
           @RequestParam(value = "admin") String admin,
           @RequestParam(value = "idnum") String idnum,
           @RequestParam(value = "warntime") String warntime,
           @RequestParam(value = "lon") String lon,
           @RequestParam(value = "lat") String lat)
    { return warnRecordEntityService.updateWarnRecord(admin, idnum, warntime, lon, lat); }
}
